// ==UserScript==
// @name         千问AI聊天文字显示优化1.3
// @namespace    http://tampermonkey.net/
// @version      1.3
// @description  聊天文本全屏拉伸+字体大小/行高滑块控制+自动收缩面板
// @author       ChatGPT
// @match        https://chat.qwen.ai/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // ===================== 滚轮速度设置 =====================
    // 滚轮滚动速度因子，数值越小滚动越慢，推荐范围0.005~0.05，默认0.01
    const qwenScrollSpeedFactor = 0.01;
    // =======================================================

    // 优化选择器，覆盖所有聊天内容
    const chatTextSelector = [
      '.user-message-text-content',
      '.user-message-text-content *',
      '.response-message-body--normal',
      '.response-message-body--normal *',
      '.ThinkingPanel__Body__Content',
      '.ThinkingPanel__Body__Content *',
      '.markdown-prose',
      '.markdown-prose *',
      '.markdown-content-container',
      '.markdown-content-container *'
    ].join(', ');
    const chatBoxSelector = '.flex.flex-col.justify-between.w-full.max-w-\\[60rem\\].group.mx-auto.rounded-lg';

    // 创建样式
    const style = document.createElement('style');
    style.textContent = `
    /* 聊天文本框全屏拉伸 - 初始样式，将被动态样式覆盖 */
    ${chatBoxSelector} {
        box-sizing: border-box !important;
        border-radius: 0 !important;
    }
    /* 内层消息容器样式 */
    .response-message-container,
    .user-message-container,
    .thinking-container,
    .markdown-container {
        width: 100% !important;
        max-width: 100% !important;
        box-sizing: border-box !important;
    }
    /* 滑块面板样式 */
    #fontControlPanel {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 99999;
        background: rgba(255,255,255,0.85);
        border-radius: 12px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.12);
        padding: 18px 22px 14px 22px;
        display: flex;
        flex-direction: column;
        gap: 12px;
        transition: opacity 0.3s, visibility 0.3s;
        min-width: 220px;
        min-height: 80px;
        font-size: 15px;
        user-select: none;
    }
    #fontControlPanel.hide {
        opacity: 0;
        visibility: hidden;
        pointer-events: none;
    }
    #fontControlDot {
        position: fixed;
        top: 28px;
        right: 28px;
        width: 32px;
        height: 32px;
        background: #2196f3;
        border-radius: 50%;
        z-index: 99999;
        box-shadow: 0 2px 8px rgba(33,150,243,0.18);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        opacity: 1;
        transition: opacity 0.3s;
    }
    #fontControlDot.hide {
        opacity: 0;
        pointer-events: none;
    }
    #fontControlPanel label {
        font-weight: bold;
        margin-bottom: 2px;
    }
    #fontControlPanel input[type=range] {
        width: 120px;
        vertical-align: middle;
    }
    #fontControlPanel .slider-row {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    `;
    document.head.appendChild(style);

    // 创建滑块面板
    const panel = document.createElement('div');
    panel.id = 'fontControlPanel';
    panel.innerHTML = `
      <div class="slider-row"><label>字体大小</label><input id="fontSizeSlider" type="range" min="5" max="45" step="2"><span id="fontSizeValue"></span>px</div>
      <div class="slider-row"><label>行高</label><input id="lineHeightSlider" type="range" min="0.5" max="5" step="0.2"><span id="lineHeightValue"></span></div>
      <div class="slider-row"><label>内容宽度</label><input id="contentWidthSlider" type="range" min="50" max="100" step="5"><span id="contentWidthValue"></span>%</div>
      <div style="margin-top:5px;"><button id="debugWidthBtn" style="padding:4px 8px;background:#f44336;color:white;border:none;border-radius:4px;cursor:pointer;">强制修复宽度</button></div>
    `;
    document.body.appendChild(panel);

    // 创建小圆点
    const dot = document.createElement('div');
    dot.id = 'fontControlDot';
    dot.title = '显示文字控制面板';
    dot.innerHTML = '<svg width="18" height="18" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8" fill="#fff" opacity="0.18"/><circle cx="12" cy="12" r="5" fill="#fff" opacity="0.28"/></svg>';
    document.body.appendChild(dot);
    dot.classList.add('hide');

    // 默认值
    let fontSize = Number(localStorage.getItem('qwen_fontSize')) || 17;
    let lineHeight = Number(localStorage.getItem('qwen_lineHeight')) || 1.9;
    let contentWidthPercent = Number(localStorage.getItem('qwen_contentWidth')) || 85;

    // 设置滑块初值
    const fontSizeSlider = panel.querySelector('#fontSizeSlider');
    const lineHeightSlider = panel.querySelector('#lineHeightSlider');
    const contentWidthSlider = panel.querySelector('#contentWidthSlider');
    const fontSizeValue = panel.querySelector('#fontSizeValue');
    const lineHeightValue = panel.querySelector('#lineHeightValue');
    const contentWidthValue = panel.querySelector('#contentWidthValue');
    fontSizeSlider.value = fontSize;
    lineHeightSlider.value = lineHeight;
    contentWidthSlider.value = contentWidthPercent;
    fontSizeValue.textContent = fontSize;
    lineHeightValue.textContent = lineHeight;
    contentWidthValue.textContent = contentWidthPercent;

    // 样式应用函数（用CSS注入方式）
    function updateFontStyle() {
        let styleTag = document.getElementById('qwen-font-style');
        if (!styleTag) {
            styleTag = document.createElement('style');
            styleTag.id = 'qwen-font-style';
            document.head.appendChild(styleTag);
        }
        // Mermaid字体统一为10px
        let mermaidFontSize = 10;
        styleTag.textContent = `
          ${chatTextSelector} {
            font-size: ${fontSize}px !important;
            line-height: ${lineHeight} !important;
          }
          /* Mermaid流程图字体统一为10px */
          .mermaid, 
          .mermaid text, 
          .mermaid .label, 
          .mermaid .nodeLabel, 
          .mermaid .edgeLabel,
          .mermaid .node rect,
          .mermaid .node circle,
          .mermaid .node ellipse,
          .mermaid .node polygon,
          .mermaid .node path,
          .mermaid .node .label,
          .mermaid .cluster rect,
          .mermaid .cluster .label,
          .mermaid .edgeWrapper .edgeLabel .label rect,
          .mermaid g.node text {
            font-size: ${mermaidFontSize}px !important;
            line-height: 1.4 !important;
          }
          
          /* 直接控制SVG中的所有文本元素 */
          .mermaid svg text,
          .mermaid svg tspan,
          .mermaid g.node text,
          .mermaid g.nodes text,
          .mermaid .node foreignObject,
          .mermaid .node foreignObject div,
          .mermaid .node foreignObject span,
          .mermaid .node > div,
          .mermaid .node > span {
            font-size: ${mermaidFontSize}px !important;
            font-family: Arial, sans-serif !important;
          }
          
          /* 确保Mermaid图表大小合适 */
          .mermaid svg {
            max-width: 100% !important;
          }
          
          /* 内层元素宽度控制，防止溢出 */
          .response-message-body--normal, 
          .user-message-text-content,
          .markdown-prose,
          .markdown-content-container,
          pre, code, table, img, svg {
            max-width: 100% !important;
            overflow-x: auto !important;
            word-wrap: break-word !important;
            word-break: break-word !important;
          }
          /* 代码块和图片特别处理 */
          pre, code {
            white-space: pre-wrap !important;
            word-break: break-word !important;
            max-width: 100% !important;
            overflow-x: auto !important;
          }
          img, svg {
            height: auto !important;
            max-width: 100% !important;
          }
          /* 表格处理 */
          table {
            display: block !important;
            table-layout: fixed !important;
            width: 100% !important;
            max-width: 100% !important;
            overflow-x: auto !important;
          }
          /* 长链接处理 */
          a {
            word-break: break-all !important;
          }
          
          /* 当页面字体较大时进一步控制Mermaid字体 */
          @media (min-width: 768px) {
            .mermaid text, 
            .mermaid .label, 
            .mermaid .nodeLabel, 
            .mermaid .edgeLabel,
            .mermaid .node rect,
            .mermaid .node circle,
            .mermaid .node ellipse,
            .mermaid .node polygon,
            .mermaid .node path,
            .mermaid .node .label,
            .mermaid .cluster rect,
            .mermaid .cluster .label,
            .mermaid .edgeWrapper .edgeLabel .label rect,
            .mermaid g.node text,
            .mermaid svg text,
            .mermaid svg tspan,
            .mermaid g.nodes text,
            .mermaid .node foreignObject,
            .mermaid .node foreignObject div,
            .mermaid .node foreignObject span,
            .mermaid .node > div,
            .mermaid .node > span {
              font-size: 10px !important;
            }
          }
        `;
    }

    // 初始应用
    setTimeout(updateFontStyle, 500);
    // 监听DOM变化，动态应用
    const observer = new MutationObserver(updateFontStyle);
    observer.observe(document.body, {childList: true, subtree: true});

    // 滑块事件
    fontSizeSlider.oninput = function() {
        fontSize = Number(this.value);
        fontSizeValue.textContent = fontSize;
        localStorage.setItem('qwen_fontSize', fontSize);
        updateFontStyle();
    };
    lineHeightSlider.oninput = function() {
        lineHeight = Number(this.value);
        lineHeightValue.textContent = lineHeight;
        localStorage.setItem('qwen_lineHeight', lineHeight);
        updateFontStyle();
    };
    contentWidthSlider.oninput = function() {
        contentWidthPercent = Number(this.value);
        contentWidthValue.textContent = contentWidthPercent;
        localStorage.setItem('qwen_contentWidth', contentWidthPercent);
        updateChatBoxWidth(); // 重新计算宽度
    };

    // 面板自动收缩逻辑
    let hideTimer = null;
    let dotHideTimer = null;
    function showPanel() {
        panel.classList.remove('hide');
        dot.classList.add('hide');
        if (hideTimer) clearTimeout(hideTimer);
        hideTimer = setTimeout(hidePanel, 8000);
    }
    function hidePanel() {
        panel.classList.add('hide');
        dot.classList.remove('hide');
    }
    function hideDot() {
        dot.classList.add('hide');
    }
    // 初始8秒后收缩
    showPanel();
    // 悬停小圆点展开
    dot.addEventListener('mouseenter', () => {
        showPanel();
    });
    // 悬停面板时不收缩
    panel.addEventListener('mouseenter', () => {
        if (hideTimer) clearTimeout(hideTimer);
    });
    // 离开面板5秒后收缩
    panel.addEventListener('mouseleave', () => {
        if (hideTimer) clearTimeout(hideTimer);
        hideTimer = setTimeout(hidePanel, 5000);
    });
    // 小圆点点击也可展开
    dot.addEventListener('click', showPanel);

    // 页面刷新时恢复设置
    window.addEventListener('DOMContentLoaded', updateFontStyle);

    // 添加调试按钮事件
    const debugWidthBtn = panel.querySelector('#debugWidthBtn');
    debugWidthBtn.addEventListener('click', () => {
        // 强制重置宽度设置
        forceFixWidth();
    });
    
    // 强制修复宽度函数
    function forceFixWidth() {
        // 直接修改DOM元素
        const mainContainers = document.querySelectorAll('.flex.flex-col.justify-between.w-full');
        if (mainContainers && mainContainers.length) {
            mainContainers.forEach(container => {
                // 强制应用宽度
                container.style.maxWidth = `${contentWidthPercent}%`;
                container.style.width = `${contentWidthPercent}%`;
                container.style.marginLeft = 'auto';
                container.style.marginRight = 'auto';
                
                // 移除可能影响宽度的类
                container.classList.remove('max-w-[60rem]');
                
                // 添加自定义标记
                container.setAttribute('data-qwen-width-fixed', 'true');
            });
        }
        
        // 查找并修复消息容器
        const messageContainers = document.querySelectorAll('.response-message-container, .user-message-container');
        if (messageContainers && messageContainers.length) {
            messageContainers.forEach(container => {
                container.style.width = '100%';
                container.style.maxWidth = '100%';
                container.style.boxSizing = 'border-box';
                container.style.paddingRight = '10px';
            });
        }
        
        // 尝试直接查找主聊天区域
        const chatMain = document.querySelector('.chat-main-container');
        if (chatMain) {
            const chatContainers = chatMain.querySelectorAll('.flex.flex-col');
            chatContainers.forEach(container => {
                if (container.classList.contains('w-full') || container.classList.contains('max-w-[60rem]')) {
                    container.style.maxWidth = `${contentWidthPercent}%`;
                    container.style.width = `${contentWidthPercent}%`;
                    container.style.marginLeft = 'auto';
                    container.style.marginRight = 'auto';
                    container.setAttribute('data-qwen-width-fixed', 'true');
                }
            });
        }
        
        // 使用控制台输出代替弹窗提示
        console.log('宽度修复已应用！');
        
        // 在面板中显示临时成功信息
        const debugBtn = document.getElementById('debugWidthBtn');
        if (debugBtn) {
            const originalText = debugBtn.textContent;
            debugBtn.textContent = '✓ 已修复';
            debugBtn.style.background = '#4CAF50';
            setTimeout(() => {
                debugBtn.textContent = originalText;
                debugBtn.style.background = '#f44336';
            }, 2000);
        }
        
        // 重新应用宽度设置
        updateChatBoxWidth();
    }

    // 完全重写宽度控制相关函数
    function updateChatBoxWidth() {
        // 获取用户设置的宽度百分比
        const widthPercent = contentWidthPercent / 100;
        
        // 直接应用宽度样式
        const styleTag = document.getElementById('qwen-chatbox-width-style') || (() => {
            const s = document.createElement('style');
            s.id = 'qwen-chatbox-width-style';
            document.head.appendChild(s);
            return s;
        })();
        
        styleTag.textContent = `
            /* 强制覆盖原有样式 */
            .flex.flex-col.justify-between.w-full.max-w-\\[60rem\\].group.mx-auto.rounded-lg,
            .flex.flex-col.justify-between.w-full.max-w-\\[60rem\\].group.mx-auto,
            .flex.flex-col.justify-between.w-full.max-w-\\[60rem\\],
            .max-w-\\[60rem\\],
            [data-qwen-width-fixed="true"],
            .chat-main-container > .flex.flex-col.w-full {
                max-width: ${widthPercent * 100}% !important;
                width: ${widthPercent * 100}% !important;
                margin-left: auto !important;
                margin-right: auto !important;
            }
            
            /* 确保内部容器也能正确显示 */
            .response-message-container,
            .user-message-container,
            .thinking-container,
            .markdown-container,
            .response-message-body--normal, 
            .user-message-text-content,
            .markdown-prose,
            .markdown-content-container {
                width: 100% !important;
                max-width: 100% !important;
                min-width: auto !important;
                box-sizing: border-box !important;
            }
            
            /* 确保代码块等特殊内容正确显示 */
            pre, code, table {
                max-width: 100% !important;
                width: auto !important;
                overflow-x: auto !important;
            }
            
            /* 调整页面整体布局 */
            .chat-container {
                width: 100% !important;
                max-width: 100% !important;
            }
            
            /* 调整内容区域边距 */
            .chat-message-container {
                padding-left: 16px !important;
                padding-right: 16px !important;
            }
            
            /* 强制覆盖任何可能影响宽度的样式 */
            [class*="max-w-"] {
                max-width: ${widthPercent * 100}% !important;
            }
        `;
        
        // 直接修改DOM元素宽度
        setTimeout(() => {
            // 查找主容器 - 使用更广泛的选择器
            const mainContainers = document.querySelectorAll('.flex.flex-col.justify-between.w-full, [data-qwen-width-fixed="true"]');
            if (mainContainers && mainContainers.length) {
                mainContainers.forEach(container => {
                    container.style.maxWidth = `${widthPercent * 100}%`;
                    container.style.width = `${widthPercent * 100}%`;
                    container.style.marginLeft = 'auto';
                    container.style.marginRight = 'auto';
                    
                    // 添加自定义标记
                    container.setAttribute('data-qwen-width-fixed', 'true');
                });
                console.log(`已应用宽度: ${widthPercent * 100}%`);
            } else {
                console.log('未找到主容器，尝试使用备用选择器');
                // 备用选择器
                const backupContainers = document.querySelectorAll('.w-full');
                if (backupContainers && backupContainers.length) {
                    backupContainers.forEach(container => {
                        if (container.classList.contains('flex-col')) {
                            container.style.maxWidth = `${widthPercent * 100}%`;
                            container.style.width = `${widthPercent * 100}%`;
                            container.style.marginLeft = 'auto';
                            container.style.marginRight = 'auto';
                            container.setAttribute('data-qwen-width-fixed', 'true');
                        }
                    });
                }
            }
            
            // 尝试直接查找主聊天区域
            const chatMain = document.querySelector('.chat-main-container');
            if (chatMain) {
                const chatContainers = chatMain.querySelectorAll('.flex.flex-col');
                chatContainers.forEach(container => {
                    if (container.classList.contains('w-full') || container.classList.contains('max-w-[60rem]')) {
                        container.style.maxWidth = `${widthPercent * 100}%`;
                        container.style.width = `${widthPercent * 100}%`;
                        container.style.marginLeft = 'auto';
                        container.style.marginRight = 'auto';
                        container.setAttribute('data-qwen-width-fixed', 'true');
                    }
                });
            }
        }, 100);
    }

    // 初始化和定期应用宽度设置
    setTimeout(updateChatBoxWidth, 100);
    setTimeout(updateChatBoxWidth, 500);
    setTimeout(updateChatBoxWidth, 1000);
    setTimeout(updateChatBoxWidth, 2000);
    
    // 页面加载完成后强制应用一次
    window.addEventListener('load', () => {
        setTimeout(updateChatBoxWidth, 500);
        setTimeout(forceFixWidth, 1000);
    });
    
    // ===================== 简化版聊天区滚动增强类 =====================
    /**
     * 简化版聊天区滚动增强类。
     * 利用 CSS pointer-events: none 策略禁用 Mermaid 交互后，
     * 滚轮事件会自然穿透到主容器，无需复杂 JS 处理。
     * 保留对代码块、表格等子区块的优先滚动支持。
     */
    class QwenChatScroller {
        constructor(options = {}) {
            this.targetSelector = options.targetSelector || '#messages-container, .chat-main-container';
            this.scrollStep = options.scrollStep || 60;
            this._onWheel = this._onWheel.bind(this);
            this._observer = null;
            this._bindedElements = new Set();
            this._applyMermaidStyleFix();
            this._init();
        }

        _init() {
            this._bindScroll();
            // 监听 DOM 变化，动态绑定所有可滚动区
            this._observer = new MutationObserver(() => {
                this._bindScroll();
            });
            this._observer.observe(document.body, { childList: true, subtree: true });
        }

        _applyMermaidStyleFix() {
            // 注入强制禁用 Mermaid 交互和缩放的样式，针对更具体的结构
            const styleId = 'qwen-mermaid-force-fix';
            if (!document.getElementById(styleId)) {
                const style = document.createElement('style');
                style.id = styleId;
                style.textContent = `
                    /* === 核心策略：禁用 Mermaid 相关容器的指针事件 === */
                    .code-cntainer .relative, /* 父容器 */
                    .svg-container,          /* SVG 容器 */
                    .svg-content,            /* IMG 元素 */
                    .mermaid,                /* 通用 .mermaid 类 */
                    [class*="mermaid"],      /* 类名包含 mermaid 的元素 */
                    [class*="svg-container"] /* 类名包含 svg-container 的元素 */
                    {
                        pointer-events: none !important; /* 关键：让事件穿透 */
                        touch-action: pan-y !important; /* 移动端只允许垂直滚动 */
                        -webkit-user-drag: none !important;
                        -khtml-user-drag: none !important;
                        -moz-user-drag: none !important;
                        -o-user-drag: none !important;
                        user-drag: none !important;
                    }
                    .code-cntainer .relative *,
                    .svg-container *,
                    .svg-content *,
                    .mermaid *,
                    [class*="mermaid"] *,
                    [class*="svg-container"] *
                    {
                        touch-action: pan-y !important;
                        zoom: reset !important;
                        -webkit-text-size-adjust: none !important;
                        -moz-text-size-adjust: none !important;
                        -ms-text-size-adjust: none !important;
                        text-size-adjust: none !important;
                        user-select: text !important;
                    }
                    .mermaid svg text,
                    .mermaid svg tspan {
                        user-select: text !important;
                    }
                `;
                document.head.appendChild(style);
            }
            // --- 持续监控和强制应用样式 ---
            if (!this._mermaidStyleObserver) {
                 this._mermaidStyleObserver = new MutationObserver((mutations) => {
                    let needsFix = false;
                    for (let mutation of mutations) {
                        if (mutation.type === 'childList') {
                            // 检查新增节点是否是相关容器
                            for (let node of mutation.addedNodes) {
                                if (node.nodeType === Node.ELEMENT_NODE) {
                                    // 检查节点本身
                                    if (this._isMermaidRelatedContainer(node)) {
                                        needsFix = true;
                                        break;
                                    }
                                    // 检查子节点
                                    if (node.querySelectorAll) {
                                        if (node.querySelector('.svg-container, .mermaid, [class*="mermaid"], [class*="svg-container"]')) {
                                            needsFix = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (needsFix) break;
                    }
                    if (needsFix) {
                        setTimeout(() => this._forceApplyPointerEventsToMermaidContainers(), 50);
                        setTimeout(() => this._forceApplyPointerEventsToMermaidContainers(), 200);
                    }
                 });

                 this._mermaidStyleObserver.observe(document.body, {
                    childList: true,
                    subtree: true
                 });
            }
        }

        // --- 辅助函数：判断元素是否为相关容器 ---
        _isMermaidRelatedContainer(el) {
             return el.classList && (
                 el.classList.contains('mermaid') ||
                 el.classList.contains('svg-container') ||
                 (el.classList.length > 0 && (
                     el.classList.toString().includes('mermaid') ||
                     el.classList.toString().includes('svg-container')
                 )) ||
                 (el.matches && (
                     el.matches('.code-cntainer .relative')
                 ))
             );
        }

        // --- 强制为相关容器设置 pointer-events: none ---
        _forceApplyPointerEventsToMermaidContainers() {
            const selectors = [
                '.mermaid',
                '.svg-container',
                '.svg-content',
                '[class*="mermaid"]',
                '[class*="svg-container"]',
                '.code-cntainer .relative'
            ];
            const elementsToFix = new Set();
            selectors.forEach(sel => {
                document.querySelectorAll(sel).forEach(el => {
                    elementsToFix.add(el);
                });
            });
            elementsToFix.forEach(el => {
                if (el.style.pointerEvents !== 'none') {
                    el.style.pointerEvents = 'none';
                    el.style.touchAction = 'pan-y';
                    el.setAttribute('draggable', 'false');
                }
            });
        }

        _bindScroll() {
            // 主聊天区及所有可滚动子区块 (不包括 .mermaid，因其事件已穿透)
            const targets = Array.from(document.querySelectorAll(this.targetSelector));
            const subSelectors = [
                'pre', 'code', 'table', '.markdown-prose', '.markdown-content-container',
                '.response-message-body--normal', '.user-message-text-content', '.ThinkingPanel__Body__Content'
                // '.mermaid'  // <-- 移除对 Mermaid 的绑定
            ];
            subSelectors.forEach(sel => {
                document.querySelectorAll(sel).forEach(el => targets.push(el));
            });
            targets.forEach(target => {
                if (!this._bindedElements.has(target)) {
                    // 注意：这里不再需要判断 target 是否为 .mermaid
                    target.addEventListener('wheel', this._onWheel, { passive: false });
                    this._bindedElements.add(target);
                }
            });
        }

        _onWheel(e) {
            // 由于 .mermaid 的 pointer-events: none，滚轮事件不会再触发到这里
            // 因此无需检查 e.target.closest('.mermaid')

            const el = e.currentTarget;
            const delta = e.deltaY > 0 ? this.scrollStep : -this.scrollStep;

            // 判断是否为子区块（如代码块、表格等）
            const isSubBlock = el !== document.querySelector(this.targetSelector) && !el.matches(this.targetSelector);

            if (isSubBlock) {
                // 子区块还能滚动则只滚动自身
                const atTop = el.scrollTop === 0 && delta < 0;
                const atBottom = el.scrollHeight - el.clientHeight - el.scrollTop <= 1 && delta > 0;
                if (!atTop && !atBottom) {
                    el.scrollTop += delta;
                    e.preventDefault();
                    e.stopPropagation();
                    return;
                }
                // 子区块已到顶/底，允许事件冒泡 (通常冒泡到主聊天区容器)
            }

            // 主聊天区兜底滚动 (包括由 Mermaid 区域穿透过来的滚轮事件)
            // 注意：这里直接滚动当前元素 el，因为它就是主容器或主容器的祖先
            // 或者更安全地查找一次主容器
            const mainChat = this._findScrollContainer(el);
            if (mainChat) {
                mainChat.scrollTop += delta;
                e.preventDefault();
                e.stopPropagation();
            }
        }

        _findScrollContainer(startEl) {
            let el = startEl;
            // 查找主滚动容器
            while (el && el !== document.documentElement) {
                if (el.matches && (el.matches('#messages-container') || el.matches('.chat-main-container') || el.matches('.scrollbar-trigger'))) {
                    if (el.scrollHeight > el.clientHeight) {
                        return el;
                    }
                }
                el = el.parentElement;
            }
            // Fallback
            return document.querySelector('.chat-main-container') || document.querySelector('#messages-container') || document.documentElement;
        }

        disconnect() {
            if (this._observer) this._observer.disconnect();
            this._bindedElements.forEach(el => {
                el.removeEventListener('wheel', this._onWheel);
            });
            this._bindedElements.clear();
            if (this._mermaidStyleObserver) {
                this._mermaidStyleObserver.disconnect();
            }
        }
    }
    // ===================== 简化版聊天区滚动增强类 END =====================
    
    // 初始化时修复滚动问题
    setTimeout(() => {
        // 启用新滚动增强类
        new QwenChatScroller({
            targetSelector: '#messages-container, .chat-main-container',
            scrollStep: 60
        });
    }, 1000);
    
    // 监听DOM变化时重新应用滚动修复
    const scrollFixObserver = new MutationObserver(() => {
        // fixScrollingIssues(); // This function is not defined in the original file
    });
    scrollFixObserver.observe(document.body, {childList: true, subtree: true});
    
    window.addEventListener('resize', updateChatBoxWidth);
    
    // 底部输入框自动隐藏/显示逻辑（带悬浮小长条）
    (function(){
        const inputAreaId = 'chat-message-input-all';
        const barId = 'showInputBar';
        let hideTimer = null;
        // 创建悬浮小长条
        function createShowBar() {
            if (document.getElementById(barId)) return;
            const bar = document.createElement('div');
            bar.id = barId;
            bar.textContent = '显示输入框';
            bar.style.cssText = `
                position: fixed;
                left: 50%;
                bottom: 24px;
                transform: translateX(-50%);
                z-index: 99999;
                min-width: 120px;
                padding: 8px 32px;
                background: rgba(33,150,243,0.7);
                color: #fff;
                border-radius: 18px;
                box-shadow: 0 2px 8px rgba(33,150,243,0.18);
                text-align: center;
                font-size: 16px;
                cursor: pointer;
                opacity: 0.85;
                display: none;
                user-select: none;
            `;
            document.body.appendChild(bar);
            // 悬停或点击显示输入区
            bar.addEventListener('mouseenter', showInputArea);
            bar.addEventListener('click', showInputArea);
        }
        function showBar() {
            const bar = document.getElementById(barId);
            if (bar) bar.style.display = 'block';
        }
        function hideBar() {
            const bar = document.getElementById(barId);
            if (bar) bar.style.display = 'none';
        }
        function showInputArea() {
            const area = document.getElementById(inputAreaId);
            if (area) area.style.display = 'block';
            hideBar();
            if (hideTimer) clearTimeout(hideTimer);
        }
        function hideInputArea() {
            const area = document.getElementById(inputAreaId);
            if (area) area.style.display = 'none';
            showBar();
        }
        function setupInputAreaAutoHide() {
            const area = document.getElementById(inputAreaId);
            if (!area) return;
            area.addEventListener('mouseenter', () => {
                showInputArea();
            });
            area.addEventListener('mouseleave', () => {
                if (hideTimer) clearTimeout(hideTimer);
                hideTimer = setTimeout(hideInputArea, 3000);
            });
        }
        // 初始绑定，且DOM变动时重试
        function trySetup() {
            if (document.getElementById(inputAreaId)) {
                createShowBar();
                setupInputAreaAutoHide();
            } else {
                setTimeout(trySetup, 1000);
            }
        }
        trySetup();
    })();
})(); 

// ===================== 聊天区滚动增强样式修正 =====================
(function() {
    const style = document.createElement('style');
    style.id = 'qwen-scroll-style-fix';
    style.textContent = `
        #messages-container,
        .chat-main-container,
        .response-message-body--normal,
        .user-message-text-content,
        .ThinkingPanel__Body__Content,
        .markdown-prose,
        .markdown-content-container,
        pre, code, table, .mermaid {
            overflow-y: auto !important;
            pointer-events: auto !important;
            z-index: auto !important;
        }
    `;
    if (!document.getElementById('qwen-scroll-style-fix')) {
        document.head.appendChild(style);
    }
})();
// ===================== 聊天区滚动增强样式修正 END ===================== 

// ===================== Mermaid 玻璃层方案 =====================
(function() {
    // 玻璃层 class 名
    const GLASS_CLASS = 'qwen-mermaid-glass';

    // 插入玻璃层并绑定事件
    function coverMermaidWithGlass() {
        document.querySelectorAll('.mermaid').forEach(mermaid => {
            // 检查是否已插入玻璃层
            if (mermaid.parentElement && mermaid.parentElement.querySelector(`.${GLASS_CLASS}`)) return;
            // 设置父容器 relative，便于绝对定位
            const parent = mermaid.parentElement;
            if (!parent) return;
            if (getComputedStyle(parent).position === 'static') {
                parent.style.position = 'relative';
            }
            // 创建玻璃层
            const glass = document.createElement('div');
            glass.className = GLASS_CLASS;
            glass.style.position = 'absolute';
            glass.style.left = mermaid.offsetLeft + 'px';
            glass.style.top = mermaid.offsetTop + 'px';
            glass.style.width = mermaid.offsetWidth + 'px';
            glass.style.height = mermaid.offsetHeight + 'px';
            glass.style.background = 'transparent';
            glass.style.zIndex = 9999;
            glass.style.pointerEvents = 'auto';
            glass.style.cursor = 'default';
            // 绑定滚轮事件
            glass.addEventListener('wheel', function(e) {
                // 查找主聊天区
                let mainChat = mermaid.closest('#messages-container, .chat-main-container');
                if (!mainChat) mainChat = document.querySelector('.chat-main-container') || document.querySelector('#messages-container') || document.documentElement;
                const delta = e.deltaY > 0 ? 60 : -60;
                mainChat.scrollTop += delta;
                e.preventDefault();
                e.stopPropagation();
            }, { passive: false });
            // 插入玻璃层
            parent.appendChild(glass);
        });
    }
    // 初始插入
    setTimeout(coverMermaidWithGlass, 500);
    // 监听 DOM 变化，动态插入
    const glassObserver = new MutationObserver(() => {
        setTimeout(coverMermaidWithGlass, 100);
    });
    glassObserver.observe(document.body, { childList: true, subtree: true });
    // 监听窗口尺寸变化，调整玻璃层尺寸
    window.addEventListener('resize', () => {
        document.querySelectorAll(`.${GLASS_CLASS}`).forEach(glass => {
            const mermaid = glass.parentElement.querySelector('.mermaid');
            if (mermaid) {
                glass.style.left = mermaid.offsetLeft + 'px';
                glass.style.top = mermaid.offsetTop + 'px';
                glass.style.width = mermaid.offsetWidth + 'px';
                glass.style.height = mermaid.offsetHeight + 'px';
            }
        });
    });
})();
// ===================== Mermaid 玻璃层方案 END ===================== 